import React from 'react';
import {
  Animated,
  SafeAreaView,
  StyleSheet,
  ScrollView,
  //   View,
  //   Text,
  StatusBar,
  TouchableOpacity,
  Dimensions,
  ProgressBarAndroid,
  NativeModules,
  DeviceEventEmitter,
  PanResponder,
} from 'react-native';

import {
  Container,
  View,
  Header,
  Left,
  Body,
  Right,
  Button,
  Title,
  Text,
} from 'native-base';

import {Immersive} from 'react-native-immersive';

var wifi = require('react-native-android-wifi');
var dimensions = Dimensions.get('window');

import {
  //   Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

import {Battery} from '../components/index';

state = {
  animating: true,
};
console.log(this.state.animating);
var USE_NATIVE_DRIVER = true;
// const App: () => React$Node = () =>
class Home extends React.Component {
  constructor(props) {
    super(props);
    this._dragX = new Animated.Value(0);
    this._transX = this._dragX.interpolate({
      inputRange: [-100, -50, 0, 50, 100],
      outputRange: [-30, -10, 0, 10, 30],
    });
    this._onGestureEvent = Animated.event(
      [{nativeEvent: {translationX: this._dragX}}],
      {useNativeDriver: USE_NATIVE_DRIVER},
    );
    this.state = {
      batteryLevel: null,
      charging: false,
      wifiArray: [],
      isEnabled: true,
      ssid: '',
      isConnected: true,
      level: 0,
      ds: [],
      backColor: 'red',
      left: 0,
      top: 100,
      // dataSource: ds,
    };
  }
  _onHandlerStateChange = event => {
    if (event.nativeEvent.oldState === State.ACTIVE) {
      Animated.spring(this._dragX, {
        velocity: event.nativeEvent.velocityX,
        tension: 10,
        friction: 2,
        toValue: 0,
        useNativeDriver: USE_NATIVE_DRIVER,
      }).start();
    }
  };

  onBatteryStatus(info) {
    console.log('batteryLevel>>>>>>');
    console.log(info.level);

    console.log('IS charging >>>>>>');
    console.log(info.isPlugged);

    this.setState({batteryLevel: info.level});
    this.setState({charging: info.isPlugged});
  }

  getBatteryLevel = callback => {
    NativeModules.BatteryStatus.getBatteryStatus(callback);
  };

  componentDidMount() {
    this._refeshWifi();

    this.getBatteryLevel(nativeBatteryLevel => {
      console.log('nativeBatteryLevel>>>>>>');
      console.log(nativeBatteryLevel);
      this.setState({
        batteryLevel: nativeBatteryLevel,
      });
    });

    NativeModules.BatteryManager.updateBatteryLevel(
      function(info) {
        this._subscription = DeviceEventEmitter.addListener(
          'BatteryStatus',
          this.onBatteryStatus.bind(this),
        );
        this.setState({batteryLevel: info.level});
        this.setState({charging: info.isPlugged});
      }.bind(this),
    );

    Immersive.on();
    Immersive.setImmersive(true);
  }

  UNSAFE_componentWillMount() {
    this._panResponse = PanResponder.create({
      // 要求成为响应者：
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,

      onPanResponderGrant: (evt, gestureState) => {
        console.log(`onPanResponderGrant`);
        this._top = this.state.top;
        this._left = this.state.left;
        this.setState({backColor: 'red'});
      },
      onPanResponderMove: (event, ges) => {
        console.log(`event = ${event}, guesture = ${ges}`);
        this.setState({
          top: this._top + ges.dy,
          left: this._left + ges.dx,
          backColor: 'blue',
        });

        console.log(`ges.dx = ${ges.dx}, ges.dy = ${ges.dy}`);
        console.log(
          `this.state.left = ${this.state.left}, this.state.top = ${
            this.state.top
          }`,
        );
      },
      onPanResponderRelease: (event, ges) => {
        this.setState({
          backColor: 'orange',
        });
        console.log('onPanResponderRelease');
        console.log(
          `this.state.left = ${this.state.left}, this.state.top = ${
            this.state.top
          }`,
        );
        if (this.state.left > 500) {
          console.log('go manage page');
          this.goToManagePage();
        }
      },
    });
    // console.log(`this._panResponse = ${this._panResponse}`);
    // console.log(
    //   `this._panResponse.panHandlers = ${this._panResponse.panHandlers}`,
    // );
  }

  componentWillUnmount() {
    this._subscription.remove();
  }

  _refeshWifi() {
    wifi.isEnabled(isEnabled => {
      this.setState({isEnabled: isEnabled});
    });

    wifi.loadWifiList(
      wifiStringList => {
        const wifiArray = JSON.parse(wifiStringList);
        // this.setState({dataSource: this.state.dataSource.cloneWithRows(wifiArray) });
        console.log('wifiArray', wifiArray);
      },
      error => {
        console.log(error);
      },
    );

    wifi.getSSID(ssid => {
      this.setState({ssid: ssid});
    });

    wifi.connectionStatus(isConnected => {
      this.setState({isConnected: isConnected});
    });

    wifi.getCurrentSignalStrength(level => {
      this.setState({level: level});
      console.log('level', level);
    });
  }

  goToManagePage = () => {
    const {navigation} = this.props;
    navigation.navigate('Manage');
  };

  render() {
    let chargingText;
    if (this.state.charging) {
      chargingText = <Text style={styles.instructions}>Charging </Text>;
    } else {
      chargingText = <Text style={styles.instructions}>Not Charging </Text>;
    }
    const {children} = this.props;
    return (
      <>
        {/* <StatusBar hidden={true} barStyle="dark-content" /> backgroundColor="pink" */}
        <StatusBar
          hidden={true}
          barStyle="light-content"
          backgroundColor="green"
        />

        <SafeAreaView>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <View style={styles.body}>
              <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>Hello React Native</Text>
                <Text style={styles.sectionTitle}>
                  BatteryLevel is {this.state.batteryLevel}
                </Text>
              </View>
            </View>

            <View style={styles.body}>
              <Button
                small
                iconRight
                transparent
                primary
                onPress={this.goToManagePage}>
                <Text>管理画面へ</Text>
              </Button>
              <Text onPress={this.goToManagePage}>管理画面へ</Text>
            </View>

            <View
              {...this._panResponse.panHandlers}
              style={{
                position: 'absolute',
                backgroundColor: this.state.backColor,
                left: this.state.left,
                top: this.state.top,
                width: 300,
                height: 300,
              }}>
              <Text>touch the rect area to page right and go manage page</Text>
              <Text>
                このエリアをタッチして、画面の右側にドロップすると、管理画面へ遷移する。
              </Text>
            </View>

            <View style={styles.example}>
              <Text>Circle Progress Indicator</Text>
              <ProgressBarAndroid animating={this.state.animating} />
              {this.state.animating ? <ProgressBarAndroid /> : null}
            </View>
            <View style={styles.sectionContainer}>
              <Text style={styles.welcome}>
                Battery Level {this.state.batteryLevel}
              </Text>
              {chargingText}
            </View>
            <View style={styles.sectionContainer}>
              <Battery
                size={60}
                percent={this.state.batteryLevel}
                color={'rgb(0,255,0)'}
              />
            </View>

            <View style={{flex: 1, flexDirection: 'column'}}>
              <Text style={{fontSize: 20, textAlign: 'center'}}>Wi-Fi APP</Text>

              <View
                style={{
                  height: 1,
                  backgroundColor: 'black',
                  width: dimensions.width,
                  marginVertical: 10,
                }}
              />

              <ScrollView
                automaticallyAdjustContentInsets={false}
                style={s.scrollView}>
                <Text style={s.text}>
                  是否开启wifi：{this.state.isEnabled == true ? '是' : '否'}
                </Text>
                <Text style={s.text}>
                  是否已连接：{this.state.isConnected == true ? '是' : '否'}
                </Text>
                <Text style={s.text}>
                  目前连接的wifi名称（ssid）：{this.state.ssid}
                </Text>
                <Text style={s.text}>连接wifi的强度：{this.state.level}</Text>
                <Text style={s.text}>扫描到的wifi信息：</Text>
              </ScrollView>

              <View
                style={{
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: 35,
                  width: dimensions.width,
                  position: 'absolute',
                  bottom: 40,
                }}>
                <TouchableOpacity
                  onPress={this._refeshWifi.bind(this)}
                  style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    height: 65,
                    backgroundColor: '#FFC125',
                    borderRadius: 10,
                  }}>
                  <Text style={s.buttom}>刷新</Text>
                </TouchableOpacity>
              </View>
            </View>
          </ScrollView>
        </SafeAreaView>
      </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  engine: {
    position: 'absolute',
    right: 0,
  },
  body: {
    backgroundColor: 'yellow',
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
  highlight: {
    fontWeight: '700',
  },
  footer: {
    color: Colors.dark,
    fontSize: 12,
    fontWeight: '600',
    padding: 4,
    paddingRight: 12,
    textAlign: 'right',
  },
  example: {
    marginVertical: 24,
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  rect: {
    width: 200,
    height: 200,
    borderWidth: 1,
    borderColor: 'black',
    position: 'absolute',
  },
});

const s = StyleSheet.create({
  text: {
    marginLeft: 50,
    paddingVertical: 5,
    fontSize: 15,
  },
  buttom: {
    width: 200,
    height: 30,
    textAlign: 'center',
    paddingVertical: 12,
    fontSize: 17,
  },
  scrollView: {
    height: 300,
  },
});

export default Home;
